package com.youbug.mall.order_oms.interceptor;

import com.youbug.common.to.UmsMemberTo;
import com.youbug.common.to.UserInfoTo;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

import static com.youbug.common.constant.AuthServerConstant.LOGIN_USER;


public class OrderInterceptor implements HandlerInterceptor {

    public static ThreadLocal<UmsMemberTo> loginUser = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String uri = request.getRequestURI();
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        boolean match = antPathMatcher.match("/mall/order/payed/notify", uri);
        if (match) {
            return true;
        }

        UmsMemberTo attribute = (UmsMemberTo) request.getSession().getAttribute(LOGIN_USER);

        if (attribute != null) {
            //把登录后用户的信息放在ThreadLocal里面进行保存
            loginUser.set(attribute);

            return true;
        } else {
            //未登录，返回登录页面
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = response.getWriter();
            out.println("<script>alert('请先进行登录，再进行后续操作！');location.href='http://auth.gulimall.com/mall/login.html'</script>");
            return false;
        }
    }
}
